package cn.gson.CRM.service.SaleService;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.CRM.model.dao.order.OrderDao;
import cn.gson.CRM.model.dao.order.OrderDetailsDao;
import cn.gson.CRM.model.dao.salemanage.QuoDetialDao;
import cn.gson.CRM.model.dao.salemanage.QuotationDao;
import cn.gson.CRM.model.entity.Order;
import cn.gson.CRM.model.entity.OrderDetail;
import cn.gson.CRM.model.entity.Product;
import cn.gson.CRM.model.entity.QuoDetail;
import cn.gson.CRM.model.entity.Quotation;
import cn.gson.CRM.model.entity.Voc;
import cn.gson.CRM.model.mapper.PlanMapper;
import cn.gson.CRM.model.mapper.QuotationMapper;

@Service
public class QuotationService
{
	@Autowired
	private QuotationDao quotationDao;

	@Autowired
	private VocService vocService;

	@Autowired
	private ChanceService chanceSer;

	@Autowired
	private QuoDetialDao quodeDao;

	@Autowired
	private QuotationMapper quotationMapper;
	
	@Autowired
	private PlanService planser;
	
	@Autowired
	private OrderDao orderDao;
	
	@Autowired
	private OrderDetailsDao detailDao;

	@Transactional
	public Quotation createQuotation(Quotation quo)
	{
		/**
		 * 生成日期
		 */
		quo.setCreateDate(new Date());
		/**
		 * 生成编号
		 */
		SimpleDateFormat dateform = new SimpleDateFormat("yyyyMMdd");

		Random ran = new Random();

		quo.setQuoId(dateform.format(new Date()) + ran.nextInt(10000));

		/**
		 * 获取机会需求总额
		 */
		List<Voc> vocs = vocService.getVocByChance(quo.getChance().getId());

		Double sum = 0.0;

		for (Voc voc : vocs)
		{
			sum += voc.getNumber() * voc.getProduct().getSellPrice();
		}

		quo.setTotal(sum);

		Quotation save = quotationDao.save(quo);

		/**
		 * 更新销售机会情况
		 */
		chanceSer.updateChanceQuote(quo.getChance().getId());

		/**
		 * 保存报表详情
		 */
		saveQuoDetail(vocs, save);
		
		
		planser.updatePlanQuo(save.getChance().getId(),save.getId());

		return save;

	}

	public void saveQuoDetail(List<Voc> vocs, Quotation quo)
	{
		/**
		 * 去除重复的voc
		 */
		HashMap<String, Voc> hashMap = new HashMap<String, Voc>();
		for (Voc voc : vocs)
		{
			if (hashMap.containsKey(voc.getProduct().getName()))
			{
				Voc voc2 = hashMap.get(voc.getProduct().getName());

				voc2.setNumber(voc.getNumber() + voc2.getNumber());

			}
			else
			{
				hashMap.put(voc.getProduct().getName(), voc);
			}
		}

		Iterator<Entry<String, Voc>> iter = hashMap.entrySet().iterator();

		/**
		 * 保存quoDetail
		 */
		while (iter.hasNext())
		{
			Entry<String, Voc> next = iter.next();

			Voc voc = next.getValue();

			QuoDetail quoDetail = new QuoDetail();

			quoDetail.setQuotation(quo);

			quoDetail.setProduct(voc.getProduct());

			quoDetail.setCount(voc.getNumber());

			quoDetail.setCost(100d);

			quodeDao.save(quoDetail);
		}

	}

	public PageInfo<Quotation> getQuotation(Integer page, Integer rows, Quotation search)
	{
		PageHelper.startPage(page, rows);

		List<Quotation> quotations = quotationMapper.getQuotation(search);

		PageInfo<Quotation> pageinfo = new PageInfo<>(quotations);

		return pageinfo;
	}

	public PageInfo<QuoDetail> getQuoDetail(Integer page, Integer rows, Long quotation)
	{
		PageHelper.startPage(page, rows);

		List<QuoDetail> quoDetail = quotationMapper.getQuoDetail(quotation);

		PageInfo<QuoDetail> pageinfo = new PageInfo<>(quoDetail);

		return pageinfo;
	}

	@Transactional
	public Integer deleteQutation(Long[] quotation)
	{
		int count = 0;
		for (Long long1 : quotation)
		{
			/**
			 * 删除需求报表明细
			 */
			this.quodeDao.deleteQuoDetail(long1);
			/**
			 * 恢复机会
			 */
			Long chance_id = this.quotationMapper.findOneByid(long1);
			chanceSer.setQuotedTo0(chance_id);

			/**
			 * 删除需求报表
			 */
			this.quotationDao.delete(long1);

			count++;
		}
		return count;
	}

	@Transactional
	public void updateCostAndCont(Double cost, Integer count, Long detailId)
	{
		quodeDao.updateCostAndCont(cost, count, detailId);;
	}

	public List<Map<String, Object>> getProduct(Long quotation)
	{
		ArrayList<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		
		List<Product> products = quotationMapper.getProductOutquo(quotation);
		
		for (Product product : products)
		{
			Map<String, Object> map= new HashMap<String, Object>();
			
			map.put("id", product.getId());
			map.put("text", product.getName());
			
			result.add(map);
		}
		
		return result;
	}
	@Transactional
	public QuoDetail saveDetail(QuoDetail quo)
	{
		
		return quodeDao.save(quo);
	}
	@Transactional
	public Long deleteDetail(Long[] detailId)
	{
		for (Long long1 : detailId)
		{
			this.quodeDao.delete(long1);
		}
		
		return null;
	}
	/**
	 * 修改报表总金额
	 * @param quotationId 报表id
	 * @param totalCount 报表总金额
	 * @return
	 * @author pshc
	 */
	@Transactional
	public Double changeTotal(Long quotationId ,Double totalCount) {
		
		HashMap<String, Object> params = new HashMap<>();
		
		params.put("quotationId", quotationId);
		params.put("totalCount", totalCount);
		
		quotationMapper.changeTotal(params);
		
		return totalCount;
	}
	/**
	 * 修改报表总金额
	 * @param quotationId 报表id
	 * @return
	 * @author pshc
	 */
	@Transactional
	public Double changeTotal(Long quotationId) {
		
		long total = this.getQuoDetail(1, 10, quotationId).getTotal();
		
		List<QuoDetail> list = this.getQuoDetail(1, (int)total, quotationId).getList();
		
		Double sum = 0.0;
		
		for (QuoDetail quoDetail : list)
		{
			sum+=quoDetail.getCount()*quoDetail.getProduct().getSellPrice()*quoDetail.getCost()*0.01;
		}
		
		
		return this.changeTotal(quotationId, sum);
	}

	public Long getQuotationId(Long detailId)
	{
		Long quotationId =  quotationMapper.getQuotationId(detailId);
		return quotationId;
	}

	public Long getQuoIdByChanceId(Long id)
	{
		return quotationMapper.getQuoIdByChanceId(id);
		
	}

	public Long getChanceIdByQuoId(Long quoteId)
	{
		
		return quotationMapper.getChanceIdByQuoId(quoteId);
	}

	public Quotation findOneQuote(Long quoteId)
	{
		List<Quotation> quotations = quotationMapper.getQuotation(new Quotation(quoteId));
		return quotations.get(0);
	}
	@Transactional
	public Order saveOrder(Order order)
	{
		order.setOrderId(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
		
		Order save = orderDao.save(order);
		
		
		return save;
		
	}
	@Transactional
	public void saveOrderDetail(Order saveOrder,Long quoteId)
	{
		List<QuoDetail> quoDetail = quotationMapper.getQuoDetail(quoteId);
		
		for (QuoDetail detail : quoDetail)
		{
			OrderDetail orderDetail = new OrderDetail();
			
			orderDetail.setOrders(saveOrder);
			
			orderDetail.setProduct(detail.getProduct());
			
			orderDetail.setCost(detail.getCost());
			
			orderDetail.setCount(detail.getCount());
			
			orderDetail.setState(1);
			
			orderDetail.setSubtotal(new BigDecimal(detail.getProduct().getSellPrice()*detail.getCost()*detail.getCount()*0.01));
			
			detailDao.save(orderDetail);
		}
		
	}
	
}
